<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>Title</title>
</head>

<body>
    您目前在<p></p>
</body>
<script>
    //定义一个空的位置构造函数
    function Location() { };
    //定义一个可以获得经纬度的方法
    Location.prototype.getLocation = function (callback) {
        var options = {
            enableHighAccuracy: true,
            maximumAge: 1000
        };
        this.callback = Object.prototype.toString.call(callback) == "[object Function]" ?
            callback :
            function (address) {
                // alert(address.province + address.city);
                console.log("getocation(callbackFunction) 可获得定位信息对象");
            };
        var self = this;
        if (navigator.geolocation) {
            //浏览器支持geolocation
            navigator.geolocation.getCurrentPosition(function (position) {
                //经度
                var longitude = position.coords.longitude;
                //纬度
                var latitude = position.coords.latitude;
                self.loadMapApi(longitude, latitude);
            }, self.onError, options);
        } else {
            //浏览器不支持geolocation
        }
    };
    //定义一个可以解析经纬度的方法，调用百度的api
    Location.prototype.loadMapApi = function (longitude, latitude) {
        var self = this;
        var oHead = document.getElementsByTagName('HEAD').item(0);
        var oScript = document.createElement("script");
        oScript.type = "text/javascript";
        oScript.src = "http://api.map.baidu.com/getscript?v=2.0&ak=sKfS9qs40a8cegV6LOxGbCSPSQOCSGTe";
        oHead.appendChild(oScript);
        oScript.onload = function (date) {
            var point = new BMap.Point(longitude, latitude);
            var gc = new BMap.Geocoder();
            gc.getLocation(point, function (rs) {
                var addComp = rs.addressComponents;
                self.callback(addComp);
            });
        }
    };
    //定义出现查询位置出现意外的方法
    Location.prototype.onError = function (error) {
        switch (error.code) {
            case 1:
                alert("位置服务被拒绝");
                break;
            case 2:
                alert("暂时获取不到位置信息");
                break;
            case 3:
                alert("获取信息超时");
                break;
            case 4:
                alert("未知错误");
                break;
        }
    };
    //调用
    var local = new Location();
    let defaultCity = local.getLocation(function (res) {
        console.log(res);
        var str = ""
        for (i in res) {
            str = res[i] + str
        }
        var reg = /.+?(省|市|自治区|自治州|县|区)/g; // 省市区的正则
        // str : 河北省保定市竞秀区乐凯北大街辅路
        // city : 河北省,保定市,竞秀区
        city = str.match(reg)
        document.querySelector("p").innerHTML = str;
    })
</script>

</html>